import { defineStore } from 'pinia'
import { ref } from 'vue'

import {getuserInfo, userLogin} from "@/api/user";
import { reqUserLoginType,UserCardInfo } from "@/api/user/type";
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import pinia from '..'
import router from "@/router";
//创建用户小仓库
const useUserStore = defineStore('User',() => {
    const token =ref<string>(GET_TOKEN() as string)

    const userInfo = ref<UserCardInfo>({
        id: 0,
        username: '',
        password: '',
        phone: '',
        nickname: '',
        sex: '',
        email: '',
        avater: '',
        createTime: '',
        updateTime: ''
      })

    async function login (userLoginType: reqUserLoginType) {
        try {
            const res1 = await userLogin(userLoginType)
            console.log(res1)
            SET_TOKEN( 'Bearer ' + res1.data)
            token.value = 'Bearer ' + res1.data
            // console.log(data)
            const res2 = await getuserInfo()
            userInfo.value = res2.data
            console.log(userInfo.value)
           // router.push('/home')

        } catch (error) {
         Promise.reject(error)
        }
    }

    return {
        token,
        userInfo,
        login
    }
})
//对外暴露获取小仓库方法
export default useUserStore

// 非setup
export function useUserStoreHook() {
    return useUserStore(pinia)
}
